package cn.e3mall.search.service.impl;

import java.util.List;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.e3mall.common.pojo.SearchItem;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.search.mapper.ItemMapper;
import cn.e3mall.search.service.SearchItemService;

@Service
public class SearchItemServiceImpl implements SearchItemService{
	
	@Autowired
	private ItemMapper itemMapper;
	
	@Autowired
	private SolrServer solrServer;
	
	@Override
	public E3Result importAllItems() {
		//查询数据库商品列表
		List<SearchItem> itemList = itemMapper.getItemList();
		
		/**
		 * 	遍历商品列表
		 * 		1.创建文档
		 * 		2.添加域到文档
		 * 		3.提交
		 * 
		 */
		try {
			for(SearchItem searchItem:itemList) {
				
				//创建文档
				SolrInputDocument document = new SolrInputDocument();
				
				//添加域到文档
				document.addField("id",searchItem.getId());
				document.addField("item_title",searchItem.getTitle());
				document.addField("item_sell_point",searchItem.getSell_point());
				document.addField("item_price", searchItem.getPrice());
				document.addField("item_image",searchItem.getImage());
				document.addField("item_category_name",searchItem.getCategory_name());
				
				//添加文档
				solrServer.add(document);
			}
			//提交
			solrServer.commit();
			
			//返回结果
			return E3Result.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return E3Result.build(500,"商品导入失败");
		}
		
	}

}
